﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Threading;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;


namespace MonitorFileConvert
{

    /// <summary>
    /// 自定义参数结构体(抓图)
    /// </summary>

    public class TEventArgs
    {
        /// <summary>
        /// 文件全路径
        /// </summary>
        public string  stringFileFullPath;
        /// <summary>
        /// 文件扩展名
        /// </summary>
        public string  stringFileExtend;
        /// <summary>
        /// 视频文件计数器
        /// </summary>
        public int intMovisFilesCount;
        /// <summary>
        /// 图片文件计数器
        /// </summary>
        public int intImageFilesCount;
        /// <summary>
        /// 发生错误
        /// </summary>
        public string stringError;

    }



    /// <summary>
    /// 处理具体事务(抓图)的线程类
    /// </summary>
    public class ThreadClass
    {
        protected Thread hThread;  //线程句柄
        protected Form _form;
        protected string _directoryPath;
        protected Random _random;
        protected List<string> _list;

        public delegate void delegateBefore(TEventArgs e);   //执行前事件委托
        public event delegateBefore BeforeHandle;

        public delegate void delegateExcuting(TEventArgs e);  //执行中事件委托
        public event delegateExcuting ExcutingHandle;

        public delegate void delegateCommit(TEventArgs e);  //提交数据事件委托
        public event delegateCommit CommitHandle;

        public delegate void delegateComplete(TEventArgs e);  //执行完成后事件委托
        public event delegateComplete CompleteHandle;

        public delegate void delegateError(TEventArgs e);  //发生错误事件委托
        public event delegateError ErrorHandle;


        public ThreadClass(Form form)
        {
            this._form = form;
        }

        public ThreadClass(Form form,string directoryPath ,Random random,List<string> list)
        {
            this._form = form;
            this._directoryPath = directoryPath;
            this._random = random;
            this._list = list;
        }



        public void Start()
        {
            hThread = new Thread(new ThreadStart(Execute));
            hThread.Start();
        }

        public void End()
        {
            if (hThread != null)
                hThread.Abort();
        }

        private void Execute()
        {
            _BeginCatchImages(_directoryPath, _random, _list);
        }

        private void _BeginCatchImages(string directoryPath, Random random, List<string> list)
        {
            System.IO.DirectoryInfo direct = new DirectoryInfo(directoryPath);
            foreach (System.IO.DirectoryInfo dir in direct.GetDirectories())
            {
                _BeginCatchImages(dir.FullName, random,list);
            }
            foreach (System.IO.FileInfo file in direct.GetFiles())
            {
                CreateImageFromFile(file, random, list);
            }
            //执行完成
            if (CompleteHandle != null)
            {
                this._form.Invoke(CompleteHandle, new object[] { new TEventArgs() });
            }

        }


        private void CreateImageFromFile(System.IO.FileInfo file, Random random, List<string> list)
        {
            try
            {
                if (list.Contains(file.Extension.Trim().ToLower()))
                {
                    //this.textMemo.Text += file.FullName + "\r\n";

                    //((TextBox)_form.Controls.Find("textMemo", true)[0]).Text += file.FullName + "\r\n";
                    TEventArgs e = new TEventArgs();
                    e.stringFileFullPath = file.FullName;
                    e.stringFileExtend = file.Extension;
                    e.intMovisFilesCount++;

                    //执行前事件
                    if (BeforeHandle != null)
                    {
                        this._form.Invoke(BeforeHandle, new object[] { e });
                    }

                    string strImage = file.Name.Replace(file.Extension, string.Empty);
                    string ss = GetRandom(random);

                    #region 生成图片 //ffmpeg.exe -i 19_11574.mp4 -y  -f image2 -ss 3  -s 160*120 tt1.jpg
                    //小图
                    string strSmallImage = file.FullName.Replace(file.Extension, "_small.jpg");
                    _CreateImage(file, "checkSmall", "textSmall", strSmallImage, ss);

                    //中图
                    string strMiddleImage = file.FullName.Replace(file.Extension, "_middle.jpg");
                    _CreateImage(file, "checkMiddle", "textMiddle", strMiddleImage, ss);


                    //大图
                    string strBigImage = file.FullName.Replace(file.Extension, "_big.jpg");
                    _CreateImage(file, "checkBig", "textBig", strBigImage, ss);
                   
                    #endregion

                    #region 生成MetaData mp4box  -isma  "E:\mediaplayer-5.9-viral\2012-hi-yxq-01.mp4"

                    _CreateMetaData(file, "ckbMetaData");

                    #endregion
                    
                    //执行中事件
                    if (ExcutingHandle != null)
                    {
                        this._form.Invoke(ExcutingHandle, new object[] { e });
                    }
                }
            }
            catch (Exception ex)
            {
                TEventArgs e = new TEventArgs();
                e.stringError = ex.Message;

                //执行前事件
                if (ErrorHandle != null)
                {
                    this._form.Invoke(ErrorHandle, new object[] { e });
                }
            }

        }

        private string GetRandom(Random random)
        {
            //Random random = new Random(System.Environment.TickCount);
            return random.Next(2, 20).ToString();
        }

        private bool _CreateImage(System.IO.FileInfo file,string checkControlName,string textControlName,string strImageFile,string ss)
        {
            bool isCreate = false;
            string strFfmpegPath = Application.StartupPath + (@"\ffmpeg.exe");
            if (((CheckBox)_form.Controls.Find(checkControlName, true)[0]).Checked)
            {
                if (((CheckBox)_form.Controls.Find("checkExist", true)[0]).Checked)//如果需忽略已存在图片的视频
                {
                    isCreate = !File.Exists(strImageFile);
                }
                else
                    isCreate = true;
            }

            if (isCreate)
            {
                string[] strSmallSize = ((TextBox)_form.Controls.Find(textControlName, true)[0]).Text.Trim().Split('*');
                string strArguments_small = "-i \"" + file.FullName + "\" -y  -ss " + ss + "  -s " + strSmallSize[0].ToString() + "*" + strSmallSize[1].ToString() + " -f image2 \"" + strImageFile + "\"";
                Tools.CreateProcess(strFfmpegPath, strArguments_small, false);
            }
            return isCreate;
        }

        /// <summary>
        /// 生成MetaData
        /// </summary>
        /// <param name="file"></param>
        /// <param name="checkControlName"></param>
        /// <returns></returns>
        private bool _CreateMetaData(System.IO.FileInfo file, string checkControlName)
        {
            bool isCreate = false;
            string strFfmpegPath = Tools.GetAppSetting("mp4box", @"C:\Program Files\GPAC\MP4Box.exe");
            if (((CheckBox)_form.Controls.Find(checkControlName, true)[0]).Checked)
            {
                isCreate = true;
            }

            if (isCreate)
            {
                string strArguments_small = "-isma  \"" + file.FullName + "\"";
                Tools.CreateProcess(strFfmpegPath, strArguments_small,true);
            }
            return isCreate;
        }



    }

}
